<script language="javascript" type="text/javascript" src="jit.js"></script>
<script language="javascript" type="text/javascript" src="ospffactory.js"></script>
<script language="javascript" type="text/javascript" src="forcedirected_parse.js"></script>
<script language="javascript" type="text/javascript" src="xmlToJson.js"></script> 
<script language="javascript" type="text/javascript" src="loadRouteTree.js"></script>
<script language="javascript" type="text/javascript" src="checkconfig.js"></script>
<script language="javascript" type="text/javascript" src="checkconfighost.js"></script>
<script language="javascript" type="text/javascript" src="txt2xml.js"></script>

<!--link href="ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet"-->
<script src="jquery.js"></script>
<script src="jquery-ui.js"></script>

<link href="http://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet">
<!--script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script-->


<style>
#infovis {
    position: relative;
    width: 80%;
    height: 100%;
}
#showJsonRoute {
	width: 100%;
	height: 2px;
	float:left;
}
span:hover{
	cursor:pointer;
}
li.addhosts:hover{
	cursor:pointer;
}
label, input { display:block; }
input.text { margin-bottom:12px; width:95%; padding: .4em; }
fieldset { padding:0; border:0; margin-top:0px; }
#dialog-form { display :none;}
.ui-widget {
    border: 1px solid #DDD;
    color: #333;
    background: repeat-x scroll 91% top rgb(240,240,240);
}
#container {
	border: 1px solid #DDD; 
	height: 470px; 
	width : 90%;
	float:left;
}
.tip {
    color: #111;
    width: 225px;
    background-color: white;
    border:1px solid #ccc;
    -moz-box-shadow:#555 2px 2px 8px;
    -webkit-box-shadow:#555 2px 2px 8px;
    -o-box-shadow:#555 2px 2px 8px;
    box-shadow:#555 2px 2px 8px;
    opacity:0.9;
    filter:alpha(opacity=80);
    font-size:10px;
    font-family:Verdana, Geneva, Arial, Helvetica, sans-serif;
    padding:7px;
}
div#menu {
	float:left;
	width:8%;
	height:470px;
	margin-right:2px;
	background-color:#A3A3A3;
}
div#messagebox { 
	margin : 10px;
}
a#loadfile {
	font-size: 14px;
	margin-bottom: 10px;
}
 input#savefile{
	margin-top: 10px;
	width:100%;
 }
 #JSONExport {
	float:left;
 } 
</style>



<?php

include 'php/CouchDBFactory.php'; 
$docId = htmlspecialchars($_POST['sourcefile']);

// we get a new CouchDB object that will use the 'pastebin' db 
$couchdb = new CouchDB('ospf_simulator');
// $couchdb = new CouchDB('ospf_simulator','ospfsimulator.couchappy.com');
 
try {
    $result = $couchdb->get_item($docId);
} catch(CouchDBException $e) {
    die($e->errorMessage()."\n");
}
$json = "";
  
$exist = "false";
if($couchdb->isDoc($result) == true and $couchdb->isDocEmpty($result) == false)
{
	$inistr = ""; $finstr = "";
	list($inistr, $finstr) = explode('"json":', $result->body);
	$json = substr($finstr,0,strlen($finstr)-2);
	$exist = "true";
}
else
{
	$json = '{ "_id": "' . $docId . '", "json": [ ] }';
}
// echo '<br>le résultat:"'.$json.'"'; 
?>

<script type="text/javascript">
jQuery(function() {
	jQuery( " a#loadfile").button();
	jQuery("button#addRouter").button();
	jQuery("button#addSwitch").button();
	jQuery("button#exportJSONEvent").button();
	jQuery("input#savefile").button();
	 
});

var routerCounter = 0;
var switchCounter = 0;
var computerCounter = 0;
var serverCounter = 0;
var phoneCounter = 0;
var tvCounter = 0;

var labelType, useGradients, nativeTextSupport, animate;

(function() {
  var ua = navigator.userAgent,
      iStuff = ua.match(/iPhone/i) || ua.match(/iPad/i),
      typeOfCanvas = typeof HTMLCanvasElement,
      nativeCanvasSupport = (typeOfCanvas == 'object' || typeOfCanvas == 'function'),
      textSupport = nativeCanvasSupport 
        && (typeof document.createElement('canvas').getContext('2d').fillText == 'function');
  //I'm setting this based on the fact that ExCanvas provides text support for IE
  //and that as of today iPhone/iPad current text support is lame
  labelType = (!nativeCanvasSupport || (textSupport && !iStuff))? 'Native' : 'HTML';
  nativeTextSupport = labelType == 'Native';
  useGradients = nativeCanvasSupport;
  animate = !(iStuff || !nativeCanvasSupport);
})();

var Log = {
  elem: false,
  write: function(text){
    if (!this.elem) 
      this.elem = document.getElementById('log');
    this.elem.innerHTML = text;
    this.elem.style.left = (500 - this.elem.offsetWidth / 2) + 'px';
  }
};

var nodeInc = 0;
var nodeTypeFirst = "";
var firstNodeAdj;
var json = "";
var exist;
var bwSerialDefault = 1544000;
var bwEthernetDefault = Math.pow(10,8);

function combo(thelist, theinput)
{
  theinput = document.getElementById(theinput);  
  var idx = thelist.selectedIndex;
  var content = thelist.options[idx].innerHTML;
  theinput.value = content;	
}
function handleClick(cb,id) {
  labelState = document.getElementById("ospfstate" + id);
  if(cb.checked)
  {
	labelState.innerHTML = "up";
  }
  else
  {
	labelState.innerHTML = "down";
  }
}

function getInterfaceType(interfaceName) {	
	return interfaceName.substring(0, interfaceName.length - 1);
}

function getBandwidth(interfaceName,value) {
	if(null == interfaceName || "undefined" == interfaceName ){return;}
	var interfaceType = getInterfaceType(interfaceName);
	if(interfaceType ==  "Se") {
		if(isNaN(parseInt(value))) {return bwSerialDefault;}
		if(value == "undefined" || null == value || value <= 0) {
			return bwSerialDefault;
		}
		else {
			return value;
		}
	}
	if(interfaceType ==  "Fa") {
		if(isNaN(parseInt(value))) {return bwEthernetDefault;}
		if(value == "undefined" || null == value || value <= 0 ) {
			return bwEthernetDefault;
		}
		else {
			return value;
		}	
	}
}

function isHost(item){
	if(item == "tv" || item == "server" || item == "phone" || item == "computer")
	{
		return true;
	}
	return false;
}


function connectionCount(adjs,connectionType){	
	var counter = 0;
	for(var id in adjs) {
		var adj = adjs[id];
		if(adj.data.type == connectionType){
			counter++;
		}
	}
	return counter;
}

function init(){
  // init data
  

  var nodeToDelete = [];
  var json = <?php echo $json; ?>;
  var docId = "<?php echo $docId; ?>";
  var exist = "<?php echo $exist; ?>";
  
  // end
  // init ForceDirected
  var fd = new $jit.ForceDirected({
    //id of the visualization container
    injectInto: 'infovis',
    //Enable zooming and panning
    //with scrolling and DnD
	'width': 1150,
    'height': 470,
    Navigation: {
      enable: true,
      type: 'Native',
      //Enable panning events only if we're dragging the empty
      //canvas (and not a node).
      panning: 'avoid nodes',
      zooming: 60 //zoom speed. higher is more sensible
    },
    // Change node and edge styles such as
    // color and width.
    // These properties are also set per node
    // with dollar prefixed data-properties in the
    // JSON structure.
    Node: {
      overridable: true,
      dim: 7
    },
    Edge: {
      overridable: true,
      color: '#23A4FF',
      lineWidth: 1
	  // ,type: 'Native'
    },
		//Add Tips  
	  Tips: {  
		enable: true,  
		onShow: function(tip, node) {  
			//count connections  
			var count = 0;
			if(node.data.$type == "router")
			{
				node.eachAdjacency(function() { count++; });
				
				  // Build the right column relations list.  
				  // This is done by traversing the clicked node connections.  
				list = [];
				//display node info in tooltip  
				node.eachAdjacency(function(adj){
					var ospfRouterToIdTemp = adj.nodeTo.data.ospfRouterId;
					var ospfRouterFromIdTemp = adj.data.nodeFromIpAddress;
					var state = adj.data.ospfstate;
					var ospfInterface = adj.data.nodeFromInterface;
					if(node.id == adj.data.nodeTo){
						ospfInterface = adj.data.nodeToInterface;
						ospfRouterFromIdTemp = adj.data.nodeToIpAddress; 
					}
					if(adj.nodeFrom != node){					
						ospfRouterToIdTemp = adj.nodeFrom.data.ospfRouterId;
					}
					list.push(ospfInterface +": " + ospfRouterFromIdTemp + "<strong>  "+ state + "</strong>" + ' => ' +adj.nodeTo.name + "-" + ospfRouterToIdTemp);
				});
				tip.innerHTML = '<div style="color: rgba(110, 110, 110, 1)"><strong>RouterId: '+node.data.ospfRouterId + '</strong><br> <div>Neighbors	 :<br>';
				for (i = 0; i < list.length; i++) {
					tip.innerHTML +=  list[i] + "<br>";
				}
				tip.innerHTML += "</div></div>";
			}
			if(node.data.$type == "switch"){
				list = [];
				//display node info in tooltip  
				node.eachAdjacency(function(adj){
					var state = adj.data.ospfstate;
					var ospfInterface = adj.data.nodeToInterface;
					var addressip = adj.data.nodeFromIpAddress;
					if(node.id == adj.data.nodeFrom){ ospfInterface = adj.data.nodeFromInterface;	}
					
					list.push(ospfInterface + ": " + addressip + "<strong>  "+ state + "</strong>" + ' => ' + adj.nodeTo.name);
				});
				tip.innerHTML = '<div style="color: rgba(110, 110, 110, 1)"> '+ node.name +' <br> <div>Neighbors	 :<br>';
				for (i = 0; i < list.length; i++) {
					tip.innerHTML +=  list[i] + "<br>";
				}
				tip.innerHTML += "</div></div>";
			}
			if(isHost(node.data.$type)){
				list = [];
				//display node info in tooltip  
				node.eachAdjacency(function(adj){
					var state = adj.data.ospfstate;
					var ospfInterface = adj.data.nodeFromInterface;
					var addressip = adj.data.nodeToIpAddress;
					
					if(node.id == adj.data.nodeTo){ ospfInterface = adj.data.nodeToInterface;	}
					
					list.push(ospfInterface + ": " + addressip + "<strong>  "+ state + "</strong>" + ' => ' + adj.nodeTo.name );
				});
				tip.innerHTML = '<div style="color: rgba(110, 110, 110, 1)"> '+ node.name +' <br> <div>Neighbors	 :<br>';
				for (i = 0; i < list.length; i++) {
					tip.innerHTML +=  list[i] + "<br>";
				}
				tip.innerHTML += "</div></div>";
				
			}
		}
	  }, 
    // Add node events
    Events: {
      enable: true,
	  enableForEdges: true,  
      type: 'Native',
      //Change cursor style when hovering a node
      onMouseEnter: function() {
        fd.canvas.getElement().style.cursor = 'move';
		deleteNodeAdj();
      },
      onMouseLeave: function() {
        fd.canvas.getElement().style.cursor = '';
      },
      //Update node positions when dragged
      onDragMove: function(node, eventInfo, e) {
        var pos = eventInfo.getPos();
        node.pos.setc(pos.x, pos.y);
        fd.plot();
      }, 
	  onRightClick: function(node, eventInfo, e) {	
	    if (node.nodeFrom) { //it's an edge		  
			// var adj = fd.graph.getAdjacence(node.nodeFrom.id,node.nodeTo.id);
			// delete adj;
			if (confirm('Are you sure you want to delete this node ?')) {
				fd.graph.removeAdjacence(node.nodeFrom.id,node.nodeTo.id);
				fd.plot();
			} else {
				// Do nothing!
			}
		} else if(node){ //it's a node			
			if(nodeTypeFirst == "") {			
				firstNodeAdj = node;
				nodeTypeFirst = firstNodeAdj.data.$type;
			}
			else if(nodeTypeFirst != "" && firstNodeAdj != node) {
				var secondNodeAdj = node;
				if( nodeTypeFirst == "router" && secondNodeAdj.data.$type ==  "router"){
					
					var counterFirstRouterCon = connectionCount(firstNodeAdj.adjacencies,"router-router");
					var counterSecondRouterCon = connectionCount(secondNodeAdj.adjacencies,"router-router");
					
					if(counterFirstRouterCon < 4 && counterSecondRouterCon < 4) {
						var n = fd.graph.addAdjacence(firstNodeAdj,secondNodeAdj,""); // nodeFrom -> nodeTo
						n.data.nodeFrom = n.nodeFrom.id;
						n.data.nodeTo = n.nodeTo.id;
						n.data.id = "adj" + Math.random();
						n.data.$color = '#EBB056';
						n.data.type = "router-router";
						n.data.nodeFromInterface = "Se" + counterFirstRouterCon;
						n.data.nodeToInterface = "Se" + counterSecondRouterCon;
						fd.plot();
						nodeTypeFirst = "";
					} else {
						alert("connection invalid");}
				}else if( nodeTypeFirst == "router" && secondNodeAdj.data.$type == "switch"){
					
					var counterRouterCon = connectionCount(firstNodeAdj.adjacencies,"switch-router");
					var counterSwitchConRouter = connectionCount(secondNodeAdj.adjacencies,"switch-router");
					var counterSwitchConHost = connectionCount(secondNodeAdj.adjacencies,"host-switch");
					if(counterRouterCon < 2 && counterSwitchConRouter < 1)
					{
						var n = fd.graph.addAdjacence(secondNodeAdj,firstNodeAdj,""); // nodeFrom => switch; nodeTo => router
						n.data.nodeFrom = n.nodeFrom.id;
						n.data.nodeTo = n.nodeTo.id;
						n.data.id = "adj" + Math.random();
						n.data.type = "switch-router";
						n.data.nodeFromInterface = "Fa"  + (counterSwitchConRouter + counterSwitchConHost);//switch
						n.data.nodeToInterface = "Fa" + counterRouterCon; // nodeTo router
						fd.plot();
						nodeTypeFirst = "";
					}else {
						alert("connection invalid");}
				
				}else if( nodeTypeFirst == "switch" && secondNodeAdj.data.$type == "router"){
					
					var counterRouterCon = connectionCount(secondNodeAdj.adjacencies,"switch-router");
					var counterSwitchConRouter = connectionCount(firstNodeAdj.adjacencies,"switch-router");
					var counterSwitchConHost = connectionCount(firstNodeAdj.adjacencies,"host-switch");
					
					if(counterRouterCon < 2 && counterSwitchConRouter < 1)
					{
						var n = fd.graph.addAdjacence(firstNodeAdj,secondNodeAdj,""); // nodeFrom => switch; nodeTo => router
						n.data.nodeFrom = n.nodeFrom.id;
						n.data.nodeTo = n.nodeTo.id;
						n.data.id = "adj" + Math.random();
						n.data.type = "switch-router";
						n.data.nodeFromInterface = "Fa" + (counterSwitchConRouter + counterSwitchConHost);//switch
						n.data.nodeToInterface = "Fa" + counterRouterCon;//router
						fd.plot();
						nodeTypeFirst = "";
					}else {
						alert("connection invalid");}
				
				}else if( isHost(nodeTypeFirst) && secondNodeAdj.data.$type == "switch"){
					
					var counterHostCon = connectionCount(firstNodeAdj.adjacencies,"host-switch");
					var counterSwitchConHost = connectionCount(secondNodeAdj.adjacencies,"host-switch");
					var counterSwitchConRouter = connectionCount(secondNodeAdj.adjacencies,"switch-router");
					
					if(counterHostCon < 1 &&  counterSwitchConHost < 19){
						var n = fd.graph.addAdjacence(firstNodeAdj,secondNodeAdj,""); // nodeFrom => host; nodeTo => switch
						n.data.nodeFrom = n.nodeFrom.id;
						n.data.nodeTo = n.nodeTo.id;
						n.data.id = "adj" + Math.random();
						n.data.type = "host-switch";
						n.data.nodeFromInterface = "Fa0"; // host
						n.data.nodeToInterface = "Fa" + (counterSwitchConHost + counterSwitchConRouter);	// switch
						fd.plot();
						nodeTypeFirst = "";
					}else{alert("connection invalid");}
					
				}else if( nodeTypeFirst == "switch" && isHost(secondNodeAdj.data.$type)){
					
					var counterHostCon = connectionCount(secondNodeAdj.adjacencies,"host-switch");
					var counterSwitchConHost = connectionCount(firstNodeAdj.adjacencies,"host-switch");
					var counterSwitchConRouter = connectionCount(firstNodeAdj.adjacencies,"switch-router");
					
					if(counterHostCon < 1 &&  counterSwitchConHost < 19){
						var n = fd.graph.addAdjacence(secondNodeAdj,firstNodeAdj,""); // nodeFrom => host; nodeTo => switch
						n.data.nodeFrom = n.nodeFrom.id;
						n.data.nodeTo = n.nodeTo.id;
						n.data.id = "adj" + Math.random();
						n.data.type = "host-switch";
						n.data.nodeFromInterface = "Fa0"; // host
						n.data.nodeToInterface = "Fa" + (counterSwitchConHost + counterSwitchConRouter); // switch
						fd.plot();
						nodeTypeFirst = "";
					}else{alert("connection invalid");}

				}
				else{alert("connection invalid");}
				nodeTypeFirst = "";
			}
		}
      },
      //Implement the same handler for touchscreens
      onTouchMove: function(node, eventInfo, e) {
        $jit.util.event.stop(e); //stop default touchmove event
        this.onDragMove(node, eventInfo, e);
      },
	  //Add also a click handler to nodes  
		onClick: function(node) {  
			if(!node) return;
			// var nodeName = prompt(" Enter Node Name ", node.name);
			// node.name = nodeName;
			// fd.plot();
			if (node.nodeFrom) { //it's an edge					
				var adj = fd.graph.getAdjacence(node.nodeFrom.id, node.nodeTo.id)
				
				var network = getNetWorkAddress(adj.data.nodeFromIpAddress,adj.data.nodeFromMask);
				alert(network);
			}
			else if (node) { //it's a node
			
				var additionalFieldHTML = "";
				var nodeType = node.data.$type;
				var nodeAdjacencies = node.adjacencies;
				var ospfRouterId = "";
				
				for(var id in nodeAdjacencies) {
					var interfaceName, addressipvalue, maskvalue, bandwidthvalue,adjtype;			
					
					var a = nodeAdjacencies[id]; 
					adjtype = a.data.type;
					
					if(null != a.data.bandwidth){
						bandwidthvalue = a.data.bandwidth;
					} else {
						bandwidthvalue = 0;
					}
					
					interfaceName = "undefined"; addressipvalue = "undefined"; maskvalue = "undefined";
					if(node.id == a.data.nodeFrom){ // if node is init node
						if(a.data.nodeFromInterface != "undefined" && null != a.data.nodeFromInterface){
							interfaceName = a.data.nodeFromInterface;
						}
						if(a.data.nodeFromIpAddress != "undefined" && null != a.data.nodeFromIpAddress){
							addressipvalue = a.data.nodeFromIpAddress;
						}
						if(a.data.nodeFromMask != "undefined" && null != a.data.nodeFromMask){
							maskvalue = a.data.nodeFromMask;
						}
					}
					else if(node.id == a.data.nodeTo){ // if node is destination node
						if(a.data.nodeToInterface != "undefined" && null != a.data.nodeToInterface){
							interfaceName = a.data.nodeToInterface;
						}
						if(a.data.nodeToIpAddress != "undefined" && null != a.data.nodeToIpAddress){
							addressipvalue = a.data.nodeToIpAddress;
						}
						if(a.data.nodeToMask != "undefined" && null != a.data.nodeToMask){
							maskvalue = a.data.nodeToMask;
						}
					}
					else {throw "error";}
					
					var dataId = a.data.id;
					var interfaceid = "interface" + dataId;
					var addressid = "addressip" + dataId;
					var maskid = "mask" + dataId;
					var bandwidthid = "bandwidth" + dataId;
					var ospfstateId = "ospfstate" + dataId;
					
					var nodeToName = a.nodeTo.name;
					var ospfRouterToId = a.nodeTo.data.ospfRouterId;
					if(a.nodeFrom != node) {
						nodeToName = a.nodeFrom.name;
						ospfRouterToId = a.nodeFrom.data.ospfRouterId;
					}
					
					var optionsSelectHTML = "";
					var ospfCost = 0;
					
					if(nodeType == "router" && adjtype == "router-router" ){						
						for (i = 0; i < 6; i++){
							optionsSelectHTML += '<option ';
							var serial = 'Se' + i;
							if(interfaceName != null && interfaceName != "undefined" ){
								if(interfaceName == serial) {
									optionsSelectHTML += ' selected="selected"';
									bandwidthvalue = getBandwidth(interfaceName,bandwidthvalue);
									ospfCost = calculCost(bandwidthvalue);
								}
							} else {
								
							}
							optionsSelectHTML +=  'value="' + serial +  '">' + serial + '</option>';
						}
					}
					
					if(isHost(nodeType)){
						optionsSelectHTML += '<option ';
						var fastEthernet = "Fa" + 0;
						optionsSelectHTML += ' selected="selected"';
						bandwidthvalue = getBandwidth(fastEthernet,bandwidthvalue);					
						ospfCost = calculCost(bandwidthvalue);
						optionsSelectHTML +=  'value="' + fastEthernet +  '">' + fastEthernet + '</option>';
					}
					else {
						for (i = 0; i < 2; i++) {
							optionsSelectHTML += '<option ';
							var fastEthernet = "Fa" + i;
							if(interfaceName == fastEthernet)
							{
								optionsSelectHTML += ' selected="selected"';
								bandwidthvalue = getBandwidth(interfaceName,bandwidthvalue);					
								ospfCost = calculCost(bandwidthvalue);
							}
							optionsSelectHTML +=  'value="' + fastEthernet +  '">' + fastEthernet + '</option>';
						}
					}
					
					var state = "down";
					var checkBoxHTML = '<input type="checkbox" onclick="handleClick(this,' + "'" + dataId + "'" + ');"><label id="' + ospfstateId + '">' + state + '</label>';
					if(null != a.data.ospfstate && a.data.ospfstate == "up")
					{
						state = "up";
						checkBoxHTML = '<input type="checkbox" onclick="handleClick(this,' + "'" + dataId + "'"+ ');"  checked><label id="' + ospfstateId + '">' + state + '</label>';
					}

					if(null != addressipvalue && "" != addressipvalue && "undefined" != addressipvalue){
						ospfRouterId = getRouterId(ospfRouterId,addressipvalue);
					}
					else{
						ospfRouterId = "";
					}
											

					if(nodeType == "router" || isHost(nodeType)){
						additionalFieldHTML += '<div style="border-width: 4px;border-style: inset;border-color: #231515;"><label for="' + interfaceid + '">Neighbor : ' + nodeToName + "<br>RouterId : " + ospfRouterToId +  '</label><br>Interface<select onChange="combo(this,' + "'" + interfaceid + "'"+ ')"> '+optionsSelectHTML+'</select>Cost: ' + ospfCost + '<br><input type="text" name="" id="' + interfaceid + '" value="' + interfaceName + '" class="text ui-widget-content ui-corner-all" disabled>  	<label for="' + addressid + '">Ip Address</label><input type="text" name="" id="' + addressid + '" value="' + addressipvalue + '" class="text ui-widget-content ui-corner-all"><label for="' + maskid + '">Mask</label> <input type="text" name="" id="' + maskid + '" value="' + maskvalue + '" class="text ui-widget-content ui-corner-all"><label for="' + bandwidthid + '">Bandwidth</label> <input type="text" name="" id="' + bandwidthid + '" value="' + bandwidthvalue + '" class="text ui-widget-content ui-corner-all">' + checkBoxHTML + '</div>';
					}
					else if(nodeType == "switch"){
						a.data.nodeFromIpAddress = egalize(a.data.nodeFromIpAddress,a.data.nodeToIpAddress);
						a.data.nodeToIpAddress = a.data.nodeFromIpAddress;
						// a.data.nodeFromInterface = egalize(a.data.nodeFromInterface,a.data.nodeToInterface);
						// a.data.nodeToInterface = a.data.nodeFromInterface;
						a.data.nodeFromMask = egalize(a.data.nodeFromMask,a.data.nodeToMask);
						a.data.nodeToMask = a.data.nodeFromMask;
						
						var ospfInterfaceSwitch = a.data.nodeToInterface;					
						if(node.id == a.data.nodeFrom){ ospfInterfaceSwitch = a.data.nodeFromInterface;	}
						
						if(adjtype == "switch-router"){ // nodeFrom => switch; nodeTo => router
							additionalFieldHTML = '<div style="border-width: 4px;border-style: inset;border-color: #231515;"> <label>Default Gateway</label><input type="text" value="' + ospfInterfaceSwitch + ": " + a.data.nodeFromIpAddress + '" class="text ui-widget-content ui-corner-all" disabled></div><div style="border-width: 4px;border-style: inset;border-color: #231515;"><label>Hosts list:</label>' + additionalFieldHTML;
						} else if(adjtype == "host-switch"){ // nodeFrom => host; nodeTo => switch
							additionalFieldHTML += '<input type="text" value="' + ospfInterfaceSwitch + ": " + a.data.nodeFromIpAddress + '" class="text ui-widget-content ui-corner-all" disabled>';
						}
					}
					
					if( isHost(nodeType)){
						additionalFieldHTML += '<div><label>Ping To:</label><input type="text" name="" id="pingto" value="" class="text ui-widget-content ui-corner-all"><button type="button" id="pingtobutton">Go!</button></div> ';
	
					}
				}
				
				if(nodeType == "switch"|| isHost(nodeType)){additionalFieldHTML += "</div>";}
				
				//Add <div>, <tr> nodeFromInterface0, nodeIpAddress0, nodeFromMask0
				var additionalField = document.getElementById("additional-field");
				additionalField.innerHTML = additionalFieldHTML;
				
				if(isHost(nodeType)){
					var ping = document.getElementById('pingtobutton');
					ping.onclick = function() {
						var addping = document.getElementById('pingto').value;
						var nodeidswitch;
						for(var id in nodeAdjacencies) {
							nodeidswitch = nodeAdjacencies[id].data.nodeFrom;
						}
						var nodeswitch = fd.graph.nodes[nodeidswitch];
						var nodeidDefaultGatway;
						for(var id in nodeswitch.adjacencies) {
							if(nodeswitch.adjacencies[id].data.type == "switch-router")
							{
								nodeidDefaultGatway = nodeswitch.adjacencies[id].data.nodeFrom;
								break;
							}
						}
						var nodedefaultgatway = fd.graph.nodes[nodeidDefaultGatway];
						var ospftable = nodedefaultgatway.data.database;
						
						ospftable = ospftable.replace(/debut/g, "<"); // &lt; .:
						ospftable = ospftable.replace(/find/g, ">"); //&gt; :.
						ospftable = ospftable.replace(/guill/g, '"'); // |||	
						
						ospftable = txt2Xml(ospftable);
						
						var allElements = ospftable.getElementsByTagName('*');
						var matchingElements = [];
						for (var ji = 0; ji < allElements.length; ji++)
						{
							var maskara = allElements[ji].getAttribute('mask');
							if(maskara != null && maskara != "undefined" ){
								maskara = getmaskfromprefix(maskara);
								var networkadj = getNetWorkAddress(addping,maskara);
								var networknode = allElements[ji].getAttribute('network')
								if (networknode == networkadj)
								{
									matchingElements.push(allElements[ji]);
								}
							}
						}
						var routes = new Array(matchingElements.length);
						for (var ji = 0; ji < matchingElements.length; ji++)
						{
							var route = [];
							route.push(matchingElements[ji].getAttribute('nodeid'));
							var parentnode = matchingElements[ji].parentNode;
							while(parentnode.nodeName == "learn"){
								route.push(parentnode.getAttribute('nodeid'));
								parentnode = parentnode.parentNode;
							}
							route.push(parentnode.getAttribute('nodeid'));
							route.push(nodedefaultgatway.id);
							route.push(nodeswitch.id);
							routes[ji] = route;
						}
						for (var ji = 0; ji< routes.length; ji++){
							for (var ij = 0; ij< routes[ji].length - 1; ij++){
								var adjtoprint = fd.graph.getAdjacence(routes[ji][ij], routes[ji][ij + 1]);
								// adjtoprint.setData('color', "#FF0000","start");
								adjtoprint.setData('color', "#7CBB00","end");
							}
						}
						fd.fx.animate({
							modes: ['edge-property:color'],
							duration: 2000
						});
					};
				}
				
				var routernameDom = jQuery("#NodeRouterName");
				
				allFields = jQuery( [] ).add( routernameDom );
				
				for(var id in nodeAdjacencies) { 	
					var dataId = nodeAdjacencies[id].data.id; 
					allFields.add(jQuery("#interface" + dataId));
					allFields.add(jQuery("#addressip" + dataId));
					allFields.add(jQuery("#mask" + dataId));
					allFields.add(jQuery("#bandwidth" + dataId));
					allFields.add(jQuery("#ospfstate" + dataId));
				}
				
				var dialog, form;
				
				function addUser() {
					allFields.removeClass( "ui-state-error" );
					node.name = routernameDom.val();
					
					var errorMessage = "";
					var advMessage = "";
						
					if(isHost(node.data.$type)){
						var nbHostUp = 0;
						for(var id in nodeAdjacencies) {
							var a = nodeAdjacencies[id];
							var dataId = a.data.id;
							
							// get address ip
							addressipvalue = document.getElementById("addressip"+dataId).value;
							
							// get bandwidth
							var bandwidthnetwork = document.getElementById("bandwidth"+dataId).value;
							
							if(addressipvalue == "undefined")
							{
								errorMessage += " Address Ip is not defined <br>";
							}
							else {
								var interfaceName = document.getElementById("interface"+dataId).value;
								a.data.bandwidth = getBandwidth(interfaceName,bandwidthnetwork);
								
								var configArray = checkConfigHost(dataId, a, id, fd, nbHostUp);
								var typeMsg = configArray[0];
								var msg = configArray[1];
								
								if(typeMsg == 'error'){
									errorMessage += msg;
								}
								else if(typeMsg == 'acknow'){
									advMessage += msg;
									nbHostUp += configArray[2]; // add interface up
								}
								var connectedinterfaceName = document.getElementById("interface"+dataId).value;
								
							}
						}
					}
					if(node.data.$type == "router"){
						
						var database = '<body name="'+ node.name + "-" + node.data.ospfRouterId  +'" limite="">';
						
						ospfRouterId = "";
						var nbRouterUp = 0;
						var interfaces = [];
						
						for(var id in nodeAdjacencies) {
							var a = nodeAdjacencies[id];
							
							var dataId = a.data.id; 
												
							// get address ip
							addressipvalue = document.getElementById("addressip"+dataId).value;
							
							
							// get router id
							ospfRouterId = getRouterId(ospfRouterId,addressipvalue);
							
							// get bandwidth
							var bandwidthnetwork = document.getElementById("bandwidth"+dataId).value;
							
							if(addressipvalue == "undefined" || ospfRouterId == "undefined")
							{
								errorMessage += " Address Ip is not defined <br>";
							}
							else {
								var interfaceName = document.getElementById("interface"+dataId).value;
								a.data.bandwidth = getBandwidth(interfaceName,bandwidthnetwork);
								
								var configArray = checkConfig(dataId,a,id,fd,nbRouterUp,interfaces);
								
								
								var typeMsg = configArray[0];
								var msg = configArray[1];
								
								if(typeMsg == 'error'){
									errorMessage += msg; 
								}
								else if(typeMsg == 'acknow'){
									advMessage += msg;
									nbRouterUp += configArray[2]; // add interface up
									database += configArray[3]; // add direct network connected 
								}
								var connectedinterfaceName = document.getElementById("interface"+dataId).value;
								interfaces.push(connectedinterfaceName);
							}
						}
						
						database += "</body>";
						var elementsstring = "";
						document.getElementById('showJsonRoute').innerHTML = "";
						if(nbRouterUp > 0){
							database = getRoute(database,fd);						
							
							var tableIpRoute = getIpRouteTable(database);
							
							document.getElementById('iproute').innerHTML = tableIpRoute;
							
							var routeJSON = xmlToJson(database);
							
							var routeJSONStr = JSON.stringify(routeJSON);
							routeJSONStr = routeJSONStr.split("limite")[1];					
							routeJSONStr = routeJSONStr.substring(6, routeJSONStr.length - 2);
							routeJSONStr = ' "name":"' + node.name + " " + ospfRouterId  + '", "data":{},' + routeJSONStr;
							routeJSONStr = '{ ' + routeJSONStr;
							routeJSONStr = routeJSONStr.replace(/null,/g,"");
							
							loadRouteTree(routeJSONStr,'showJsonRoute');	
							
							var xmlText = new XMLSerializer().serializeToString(database);
							
							
							// document.getElementById('xmlTextNode').innerHTML = xmlText;
							
							var xmlText0 = xmlText.replace(/"/g, "guill"); // |||	guill
							xmlText0 = xmlText0.replace(/</g, "debut"); // &lt; .: debut
							xmlText0 = xmlText0.replace(/>/g, "find"); //&gt; :. fin
							
							
							// var xmlTextNode = document.createTextNode(xmlText);
							node.data.database = xmlText0;
							// node.data.database = "caca";
						}
						
						node.data.ospfRouterId = ospfRouterId;
					} else if(node.data.$type == "switch"){
						
						
					}
					
					jQuery( "#ErrorMessage" ).html(errorMessage);
					jQuery( "#AdvMessage" ).html(advMessage);
					
					dialog.dialog( "close" );
					return true;
				}
				 
				dialog = jQuery( "#dialog-form" ).dialog({
					autoOpen: false,
					height: 500,
					width: 300,
					title: "Edit " +node.name,
					modal: true,
					buttons: {
						"Ok": addUser,
						Cancel: function() {
							dialog.dialog( "close" );
						}
					},
					close: function() {
						form[ 0 ].reset();
						allFields.removeClass( "ui-state-error" );
					}
				});
				form = dialog.find( "form" ).on( "submit", function( event ) {
					event.preventDefault();
					addUser();
				});
								
				// node.data.ospfRouterId = ospfRouterId;
				node.data.ospfRouterId = ospfRouterId;	
				if(nodeType == "router"){jQuery( "#NodeRouterId" ).html("Router Id = " + ospfRouterId);}
				
				jQuery( "#NodeRouterName" ).val(node.name);
				jQuery( "#ospfstate" ).val(state);
				dialog.dialog( "open" );
			}
		}
    },
    //Number of iterations for the FD algorithm
    iterations: 200,
    //Edge length
    levelDistance: 130,
    // This method is only triggered
    // on label creation and only for DOM labels (not native canvas ones).
    onCreateLabel: function(domElement, node){
      // Create a 'name' and 'close' buttons and add them
      // to the main node label
      var nameContainer = document.createElement('span'),
          closeButton = document.createElement('span'),
          style = nameContainer.style;
      nameContainer.className = 'name';
	  nameContainer.setAttribute("id", "label" + node.id);
      nameContainer.innerHTML = node.name;
      closeButton.className = 'close';
      closeButton.innerHTML = '  x';
      domElement.appendChild(nameContainer);
      domElement.appendChild(closeButton);
      style.fontSize = "0.8em";
      style.color = "#646464";

	  // domElement.onclick = function(){
		 
	  // };
	  
      //Fade the node and its connections when
      //clicking the close button 
      closeButton.onclick = function() {
		if (confirm('Are you sure you want to delete this item ?')) {
			//node deletion
			node.setData('alpha', 0, 'end');
			
			nodeToDelete.push(node);
			// fd.graph.removeNode(node.id);     
			//adjacencies deletion
			node.eachAdjacency(function(adj) { 
			  adj.setData('alpha', 0, 'end'); 
			  // fd.graph.removeAdjacence(adj.nodeFrom.id,adj.nodeTo.id);		  
			});
			fd.fx.animate({
			  modes: ['node-property:alpha',
					  'edge-property:alpha'],
			  duration: 500
			});
			// fd.reposition();
			// fd.plot();
		} else {
			// Do nothing!
		}
      };
      //Toggle a node selection when clicking
      //its name. This is done by animating some
      //node styles like its dimension and the color
      //and lineWidth of its adjacencies.
      nameContainer.onclick = function() {
        //set final styles
        fd.graph.eachNode(function(n) {
          if(n.id != node.id) delete n.selected;
          n.setData('dim', 7, 'end');
		  
          n.eachAdjacency(function(adj) {
            adj.setData('labeltext', '');
			adj.setDataset('end', {
              lineWidth: 1
				// ,color: '#23a4ff'
            });
          });
        });
        if(!node.selected) {
          node.selected = true;
          node.setData('dim', 17, 'end');
		  
          node.eachAdjacency(function(adj) {
			if(adj.data.nodeFromIpAddress != null && adj.data.nodeFromMask != null && adj.data.nodeToIpAddress != null && adj.data.nodeToMask != null){
				var network1 = getNetWorkAddress(adj.data.nodeFromIpAddress,adj.data.nodeFromMask);
				var network2 = getNetWorkAddress(adj.data.nodeToIpAddress,adj.data.nodeToMask);
				if(network1 == network2){
					var prefix = getmaskprefix(adj.data.nodeToMask);
					adj.setData('labeltext', network2 + "/" + prefix);
					// fd.refresh();
				}else{ 
					adj.setData('labeltext', 'error');
				}
			} else {adj.setData('labeltext', 'undefined');}
			
			adj.setDataset('end', {
              lineWidth: 1
				// ,color: '#36acfb'
            });
          });
        } else {
			delete node.selected;
        }
        //trigger animation to final styles
        fd.fx.animate({
          modes: ['node-property:dim',
                  'edge-property:lineWidth:color'],
          duration: 500
        });
		
        // Build the right column relations list.
        // This is done by traversing the clicked node connections.
        // var html = "<h4>" + node.name + "</h4><b> connections:</b><ul><li>",
            // list = [];
        // node.eachAdjacency(function(adj){
          // if(adj.getData('alpha')) list.push(adj.nodeTo.name);
        // });
        // append connections information
        // $jit.id('inner-details').innerHTML = html + list.join("</li><li>") + "</li></ul>";
      };
    },
    // Change node styles when DOM labels are placed
    // or moved.
    onPlaceLabel: function(domElement, node){
		var style = domElement.style;
		var left = parseInt(style.left);
		var top = parseInt(style.top);
		var w = domElement.offsetWidth;
		style.left = (left - w / 2) + 'px';
		style.top = (top + 20) + 'px';
		style.display = '';	
		// domElement.innerHTML = node.name; 
    }
  });
	
  // load JSON data.
  if(exist == 'true'){
		// load JSON data.  
	// json = eval( '(' + json + ')' );
	fd.loadJSON(json);  
	// fd.refresh();
	// // compute positions incrementally and animate.  
	fd.computeIncremental({  
	  iter: 40,  
	  property: 'end',  
	  onStep: function(perc){  
		// Log.write(perc + '% loaded...');  
	  },  
	  onComplete: function(){  
		// Log.write('done');  
		fd.animate({  
		  modes: ['linear'],  
		  transition: $jit.Trans.Elastic.easeOut,  
		  duration: 2500  
		});  
	  }  
	});
  }

// Add an event handler to the add button for
// adding a Node
	var addButton = document.getElementById('addRouter');  
	addButton.onclick = function() {
		exist = addElement("router","#EBB056",routerCounter,exist);
		routerCounter++;	
	};
	
	// Add an event handler to the add button for  
	// adding a Node
	var addSwitchButton = document.getElementById('addSwitch');  
	addSwitchButton.onclick = function() {		
		exist = addElement("switch","#393",switchCounter,exist);
		switchCounter++;		
	};
	
	var exportJson = document.getElementById('exportJSONEvent');
	exportJson.onclick = function() {	
		deleteNodeAdj();
		if(fd.root != null){
			var jsonArray = fd.toJSON('graph');		
			var stringJSONArray  = parseForceDirected(jsonArray, docId, fd);
			document.getElementById('JSONExport').innerHTML = stringJSONArray;
		}
		else {
			document.getElementById('JSONExport').innerHTML = "JSON empty";
		}
	};
	

	// jQuery(document).ready(function(){
	jQuery('#savefile').click(function(){
		// var jsonExport = $('#JSONExport').html();
		deleteNodeAdj();
		var stringJSONArray;
		if(fd.root != null)
		{
			// get json from graph
			var jsonArray = fd.toJSON('graph');		
			// convert json to string
			stringJSONArray  = parseForceDirected(jsonArray, docId, fd);
		}
		else{
			stringJSONArray = '{ "_id": "' + docId + '", "json": [ ] }';
		}
		var clickBtnValue = $(this).val();
		var ajaxurl = 'ajax.php',
		
		data =  {'action': stringJSONArray};
		$.post(ajaxurl, data, function (response) {
			// Response div goes here.
			alert("Saved");
		});
	});
	// });

	
	function deleteNodeAdj()
	{
		for(var no = 0; no < nodeToDelete.length; no++)
		{			
			var nodeDelete = nodeToDelete[no];
			nodeDelete.eachAdjacency(function(adj) {
				fd.graph.removeAdjacence(adj.nodeFrom.id,adj.nodeTo.id);		  
			});
			fd.graph.removeNode(nodeDelete.id);
			if(fd.root == nodeDelete.id)
			{
				fd.root = null;
				fd.graph.eachNode(function(node) { 
					if(node.id != nodeDelete){
						fd.root = node.id;
					}
				});
			}
		}		
		nodeToDelete = [];
	}

	// do not forget incremante counter after function
	function addElement(type,color,counter,exist){
		deleteNodeAdj();
		
		var elementName = type + " " + counter;	
		var elementId = "node" + Math.random();
		if(exist == 'true') {
			var n = fd.graph.addNode({id: elementId,name: elementName });
			n.getPos().setc(10, 10);
			n.data.$type = type;
			n.data.$color = color;
			if(null == fd.root || fd.root == "undefined"){fd.root = elementId;}
			fd.plot();
		} else {
			json = ' { "id": "' + elementId + '", "name": "' + elementName + '", "data": { "$color": "'+ color +'", "$type": "' + type + '", "posX": "10", "posY": "10"}, "adjacencies": [ ] }  ';
			
			fd.loadJSON(eval( '(' + json + ')' ));
			fd.refresh();
			
			exist = 'true';	
		}
		return exist;
	}
	
	jQuery(document).ready(function() {
	  jQuery(window).keydown(function(event){
		if(event.keyCode == 13) {
		  event.preventDefault();
		  return false;
		}
	  });
	});

	jQuery(function() {
		jQuery( "#addhost" )
		.button({
			text: true
			// icons: {
				// primary: "ui-icon-triangle-1-s"
			// }
		})
		.click(function() {
			var menu = $( this ).parent().next().show().position({
				my: "bottom right",
				at: "right bottom",	
				// my: "left top",
				// at: "left bottom",
				of: this
			});
			jQuery( document ).one( "click", function(e) {
				var addtype = e.target.id;
				if(addtype == "addtv"){
					exist = addElement("tv","#EBB056",tvCounter,exist);
					tvCounter++;
				}else if (addtype == "addcomputer"){
					exist = addElement("computer","#EBB056",computerCounter,exist);
					computerCounter++;
				}else if (addtype == "addserver"){
					exist = addElement("server","#EBB056",serverCounter,exist);
					serverCounter++;
				}else if (addtype == "addphone"){
					exist = addElement("phone","#EBB056",phoneCounter,exist);
					phoneCounter++;	
				}
				
				menu.hide();
			});
			return false;
		})
		.parent()
			.buttonset()
			.next()
				.hide()
				.menu();
	});	
}

</script>

<body onload="init();">
<div>
<div id="menu">
<a href="loadfile.php" id="loadfile"> Open New Model<a> <br>
<button type="button" id="addRouter">Add Router</button> 
<button type="button" id="addSwitch">Add Switch</button>
<div>
	<div>
		<button id="addhost"> Add host</button>
	</div>
	<ul>
		<li id="addcomputer" class="addhosts">Computer</li>
		<li id="addserver" class="addhosts">Server</li>
		<li id="addtv" class="addhosts">TV</li>
		<li id="addphone" class="addhosts">Phone</li>
	</ul>
</div>


<button type="button" id="exportJSONEvent">Show JSON</button> 
<input style="display:inline-block;" id="savefile" type="submit" class="button" name="select" value="SAVE" /><br>	


</div>

<div id="container">	
		

	<div id="infovis"></div>	
	<div id="log"></div>
	<div id="test"></div>
	
	<div id="dialog-form" title=""> 
		<form>
			<fieldset>
				<label id="NodeRouterId" ></label>
				<label for="NodeRouterName">Router Name</label>
				<input type="text" name="node" id="NodeRouterName" value="" class="text ui-corner-all ui-widget"> 
								
				<div id="additional-field"></div>
				
				<!-- Allow form submission with keyboard without duplicating the dialog button -->
				<input type="submit" tabindex="-1" style="position:absolute; top:-1000px">
			</fieldset>
		</form>
	</div>
</div>
<div id="messagebox">
<div style="color: red;" id="ErrorMessage"></div>
<div style="color: green;" id="AdvMessage"></div>
</div>
<div id="showJsonRoute"></div>
<div id="JSONExport"></div>
<div id="iproute"></div>
<!--iframe style="width:1200px;height:500;" src="" id="xmlTextNode"></iframe-->
</div>
</body>
